package com.zhixi.controller;

/**
 * @ClassName EmployeeController
 * @Author zhangzhixi
 * @Description
 * @Date 2022-7-8 17:14
 * @Version 1.0
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhixi.common.R;
import com.zhixi.common.SharedVariablesCurrent;
import com.zhixi.pojo.Employee;
import com.zhixi.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    //@RequestBody 主要用于接收前端传递给后端的json字符串（请求体中的数据）
    //HttpServletRequest request作用：如果登录成功，将员工对应的id存到session一份，这样想获取一份登录用户的信息就可以随时获取出来
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.将页面提交的密码进行MD5加密处理
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        //2.根据页面提交的用户名username查询数据库
        Employee emp = employeeService.getOne(new LambdaQueryWrapper<Employee>().eq(Employee::getUsername, employee.getUsername()));
        //3.如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("用户名不存在");
        }
        //4.密码比对，如果不一致则返回登录结果
        if (!password.equalsIgnoreCase(emp.getPassword())) {
            return R.error("密码错误");
        }
        //5.查看员工状态，如果已为禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("员工已禁用");
        }
        //6.登录成功，将员工id存入session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    @PostMapping("logout")
    public R<String> louOut(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("已退出");
    }


    /**
     * 添加员工
     *
     * @param request  HttpServletRequest对象
     * @param employee 员工对象
     * @return R结果对象
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工的信息：{}", employee.toString());
        //设置初始密码，需要进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));


//       employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //强转为long类型
//        Long empID = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empID);
//        employee.setUpdateUser(empID);

        employeeService.save(employee);
        return R.success("添加员工成功");
    }


    /**
     * 分页查询员工
     * @param page 分页对象
     * @param pageSize 每页显示的条数
     * @param name 员工名称
     * @return R结果对象
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, @RequestParam(required = false) String name) {
        log.info("page = {}, pageSize = {}, name = {}",page,pageSize,name);
        Page<Employee> pageInfo = new Page(page, pageSize);

        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改员工状态
     * @param request HttpServletRequest对象
     * @param employee 员工对象
     * @return R结果对象
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
        log.info(employee.toString());

//        Long empID = (Long)request.getSession().getAttribute("employee");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empID);
        employeeService.updateById(employee);
        return R.success("员工修改信息成功");
    }

    /**
     * 编辑员工
     * @param id 员工id
     * @return R结果对象
     */
    @GetMapping("/{id}")
    public R<Employee> modifyEmploy(@PathVariable("id") Long id){
        Employee employee = employeeService.getById(id);
        if (employee == null){
            return R.error("员工不存在");
        }
        return R.success(employee);
    }
}
